package test.serverframe.armc.server.manager.service.exec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.serverframe.armc.server.manager.domain.IntegrationTestInterface;
import test.serverframe.armc.server.manager.domain.IntegrationTestRecord;
import test.serverframe.armc.server.manager.service.IntegrationTestService;
import test.serverframe.armc.server.manager.service.exec.params.IntegrationTestParams;
import test.serverframe.armc.server.manager.service.exec.params.InterfaceTestParams;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LeiZhenYang
 * @date 2019.01.05
 */
public class IntegrationTester implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(IntegrationTester.class);

    private IntegrationTestParams params;

    public IntegrationTester(IntegrationTestParams params) {
        this.params = params;
    }

    @Override
    public void run() {
        IntegrationTestRecord record = new IntegrationTestRecord();
        try {
            logger.info("集成测试：" + params.getItId() + " 开始");
            // 保存集成测试记录
            record.setId(params.getItrId());
            record.setItId(params.getItId());
            record.setStartTime(new Date());
            record.setTotal(params.getTotalCount());
            record.setSuccessTotal(0);
            record.setConcurrentCount(params.getConcurrentCount());
            // 循环接口
            for (IntegrationTestInterface inter : params.getInterfaces()) {
                // 回调总数
                AtomicInteger concurrentInterfaceCallbackTotalCounter = new AtomicInteger(0);
                // 成功总数
                AtomicInteger concurrentInterfaceSuccessTotalCounter = new AtomicInteger(0);
                // 执行接口测试
                InterfaceTestParams params = new InterfaceTestParams(this.params);
                params.setTestInterface(inter);
                params.setConcurrentInterfaceTestCallbackTotalCounter(concurrentInterfaceCallbackTotalCounter);
                params.setConcurrentInterfaceTestSuccessTotalCounter(concurrentInterfaceSuccessTotalCounter);
                params.setIntegrationTestTotalCount(params.getTotalCount() / params.getExecuteCount());
                IntegrationTestService.service.submit(new InterfaceTester(params));
            }
            record.setStatus(IntegrationTestRecord.Status.Working);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            record.setStatus(IntegrationTestRecord.Status.Failure);
        } finally {
            params.getIntegrationTestRecordService().insertSelective(record);
        }
    }
}
